package com.dut.bbs.adapter;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.dut.bbs.R;
import com.dut.bbs.async.URLImageParser;
import com.dut.bbs.util.Settings;
import com.dut.bbs.util.URLConstant;

public class ThreadAdapter extends BaseAdapter {

	private List<Map<String, String>> ItemList;
	private LayoutInflater mInflater;
	private Handler handler;
	private ProgressDialog progressDialog;
	public ThreadAdapter(Context context, List<Map<String, String>> ItemList,Handler handler,ProgressDialog progressDialog) {
		this.ItemList = ItemList;
		mInflater = LayoutInflater.from(context);
		this.handler = handler;
		this.progressDialog = progressDialog;
	}

	@Override
	public int getCount() {
		return ItemList.size();
	}

	@Override
	public Object getItem(int arg0) {
		return ItemList.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		Log.v("tag_thread", position + "");
		ThreadViewHolder holder = null;
//		ImageGetter imgGetter = new Html.ImageGetter() {
//            @Override
//            public Drawable getDrawable(String source) {
//                  Drawable drawable = null;
//                  try {
//                	  InputStream is = (InputStream) new URL(source).getContent();
//                	  drawable = Drawable.createFromStream(is, "pic");
//                	  drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
//                			  .getIntrinsicHeight());
//                	  is.close();
//                	  return drawable;
//				}catch (Exception e) {
//					Log.v("ITEM", e.toString());
//					return null;
//				}            
//            }
//		};
		Map<String, String> dataMap = ItemList.get(position);
		if (convertView == null) {
			holder = new ThreadViewHolder(dataMap,mInflater.getContext(),handler,progressDialog);
			convertView = mInflater.inflate(R.layout.thread_list_item, null);
			holder.tv_title = (TextView) convertView.findViewById(R.id.item_tv_title);
			holder.tv_content = (TextView) convertView.findViewById(R.id.item_tv_content);
			holder.tv_date = (TextView) convertView.findViewById(R.id.item_tv_date);
			holder.tv_id = (TextView) convertView.findViewById(R.id.item_tv_id);
			holder.tv_reply = (TextView) convertView.findViewById(R.id.item_tv_reply);
//			holder.tv_mail = (TextView) convertView.findViewById(R.id.item_tv_mail);
			convertView.setTag(holder);
		} else {
			holder = (ThreadViewHolder) convertView.getTag();
		}	
		holder.tv_title.setText(dataMap.get("title")+":");
		if(position==0)
			holder.tv_date.setText(dataMap.get("topic")+"\n发信于:" + dataMap.get("time"));
		else
			holder.tv_date.setText("发表于:" + dataMap.get("time"));
		holder.tv_id.setText(dataMap.get("author"));
		holder.init(dataMap.get("author"));
		URLImageParser p = new URLImageParser(handler, mInflater.getContext());
//		Spanned span1 = Spannable.Factory.getInstance().newSpannable(Html.fromHtml(getContentString(dataMap), p, null));
		holder.tv_content.setText(Html.fromHtml(getContentString(dataMap), p, null));
		holder.tv_content.setMovementMethod(LinkMovementMethod.getInstance());
//		holder.tv_content.setText(Html.fromHtml(getContentString(dataMap),imgGetter,null));
		Spannable sp = (Spannable) holder.tv_content.getText();
		ImageSpan[] images = sp.getSpans(0, holder.tv_content
				.getText().length(), ImageSpan.class);
		for (ImageSpan span : images) {
			final String image_src = span.getSource();
			if(image_src.matches("http://bbs.dlut.edu.cn/nforum/img/ubb/em.*"))
				continue;
			final int start = sp.getSpanStart(span);
			final int end = sp.getSpanEnd(span);
			ClickableSpan click_span = new ClickableSpan() {

				@Override
				public void onClick(View widget) {
					String filePath = URLConstant.FILEDIR_BASE
							+ String.valueOf(image_src.hashCode());
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.setType("image/*");
					intent.setDataAndType(Uri.fromFile(new File(filePath)), "image/*");
					mInflater.getContext().startActivity(intent);
				}
				
			};
			ClickableSpan[] click_spans = sp.getSpans(start, end,
					ClickableSpan.class);
			if (click_spans.length != 0) {
				for (ClickableSpan c_span : click_spans) {
					sp.removeSpan(c_span);
				}
			}
			sp.setSpan(click_span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return convertView;
	}
	
	private String getContentString(Map<String, String> dataMap) {
		String html = dataMap.get("info");
		Document doc = null;
		doc = Jsoup.parse(html); 
		if(Settings.showPic){
			Elements eles = doc.getElementsByTag("img");
			for (Element e : eles) {
				String uri = e.attr("src");
				if (!uri.startsWith("http"))
					e.attr("src", URLConstant.URL_BASE + uri);
				// Log.v("ADAPTERURL", e.attr("src"));
			}
		}else{
			Elements eles = doc.getElementsByTag("img");
			for (Element e : eles) {
				String uri = e.attr("src");
				if (!uri.startsWith("http")){
					if(uri.matches("^/nforum/img/ubb/em.*"))
						e.attr("src", URLConstant.URL_BASE + uri);
					else
					{
						e.attr("del", "1");
						e.after(URLConstant.URL_BASE + uri+"\n");
					}

				}
				else{
					e.attr("del", "1");
					e.after(uri+"\n");
				}
			}
			doc.select("img[del=1]").remove();
		}
		html = doc.html();
//		Log.v("ITEM", html);
		return html;
	}
}